margin屬性若只有兩個參數,前者代表top和bottom,後者代表left和right,所以margin:0 auto
表示上下邊距為0,左右根據寬度自適應相同值(居中)。
生效條件
display:block
,再給要居中的元素設置寬度(ex:span,a,strong...)display:block
,自帶寬度可以不用設置(ex:button,img...)範例
// css(block element)
.parent{
width: 500px;
height: 100px;
border:2px solid green;
}
.child{
width: 100px;
height: 30px;
margin: 0 auto;
border:2px solid blue;
}
// css(inline element)
.parent{
width: 500px;
height: 100px;
border:2px solid green;
}
.child{
width: 100px;
height: 30px;
margin: 0 auto;
display: block;
border:2px solid blue;
}
// css(inline-block element)
.parent{
width: 500px;
height: 100px;
border:2px solid green;
}
.child{
margin: 0 auto;
display: block;
}
// body(block element)
<div class="parent">
<div class="child"></div>
</div>
// body(inline element)
<div class="parent">
<span class="child"></span>
</div>
// body(inline-block element)
<div class="parent">
<button class="child"></button>
</div>
結果
block element
inline element
inline-block element